<template>
    <div class="user">
        <div class="bg_thead p-2 border form-inline" >
            用户名：<input type="text" name="uname" id="user_uname" v-model="username" class="form-control">
            工号：<input type="text" name="uid" id="user_id" v-model="userId" class="form-control">
            <button class="bt btn" @click="getL()">查询</button>
            <button class="bt btn" @click="clear">重置</button>
            <button class="bt btn"  @click="getShare()">分配角色</button>

            <el-dialog title="分配角色" :visible.sync="dialogTableVisible">
                <el-form :model="share">
                    <el-form-item label="角色：" :label-width="formLabelWidth"  style="width: 40%;" prop="selectedOptionsT">
                        <el-cascader :options="optionsT" v-model="share.selectedOptionsT" style="width: 100%;" :props="props">
                        </el-cascader>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="dshare()">取 消</el-button>
                  <el-button type="primary" @click="submitShare()" >确 定</el-button>
                </div>
              </el-dialog>
              

            <button class="bt btn" @click="getAll()">+新增用户</button>

            <el-dialog :title="title" :visible.sync="dialogFormVisible">
            <el-form :model="form" style="height: 400px;" :rules="rules" ref="form">
            <el-col :span="12">
                <el-form-item label="用户工号：" :label-width="formLabelWidth" style="width: 100%;" prop="userId">
                    <el-input v-model.number="form.userId" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="性别：" :label-width="formLabelWidth"  style="width: 100%;" prop="sex">
                    <el-radio-group v-model="form.sex">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="直属上级：" :label-width="formLabelWidth"  style="width: 100%;" prop="regionselected">
                    <el-select v-model="form.regionselected" placeholder="请选择上级" style="width: 100%" filterable remote id="cortxt"> 
                        <el-option :label="item.username" :value="item.userId" v-for="item in form.region" :key="item.userId"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="电子邮件：" :label-width="formLabelWidth"  style="width: 100%;" prop="email">
                    <el-input v-model="form.email" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="入职时间：" :label-width="formLabelWidth" style="width:100%;" prop="entry"> 
                    <el-date-picker type="date" placeholder="选择日期" v-model="form.entry" style="width: 100%;" ></el-date-picker>
                </el-form-item>

                <el-form-item label="级别：" :label-width="formLabelWidth"  style="width: 100%;" prop="gradeselected">
                    <el-select v-model="form.gradeselected" placeholder="请选择级别" style="width: 100%;">
                        <el-option :label="item.label" :value="item.label" v-for="item in form.grade" :key="item.value"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="薪水：" :label-width="formLabelWidth" style="width: 100%;" prop="salary">
                    <el-input v-model.number="form.salary" autocomplete="off"></el-input>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                    <el-form-item label="姓名：" :label-width="formLabelWidth" style="width: 100%;" prop="name">
                        <el-input v-model="form.name" autocomplete="off"></el-input>
                    </el-form-item>
    
                    <el-form-item label="用户部门：" :label-width="formLabelWidth"  style="width: 100%;" prop="selectedOptions">
                        <el-cascader :options="options" v-model="form.selectedOptions" style="width: 100%;">
                        </el-cascader>
                    </el-form-item>

                    <el-form-item label="联系电话：" :label-width="formLabelWidth"  style="width: 100%;" prop="tel">
                        <el-input v-model.number="form.tel" autocomplete="off"></el-input>
                    </el-form-item>
    
                    <el-form-item label="出生年月：" :label-width="formLabelWidth" style="width:100%;" prop="birth"> 
                        <el-date-picker type="date" placeholder="选择日期" v-model="form.birth" style="width: 100%;" ></el-date-picker>
                    </el-form-item>
    
                    <el-form-item label="公司：" :label-width="formLabelWidth"  style="width: 100%;"  prop="companyselected">
                        <el-select v-model.number="form.companyselected" placeholder="请选择公司" style="width: 100%;">
                            <el-option :label="item.companyName" :value="item.companyId" v-for="item in form.company" :key="item.companyId"></el-option>
                        </el-select>
                    </el-form-item>
    
                    <el-form-item label="岗位：" :label-width="formLabelWidth"  style="width: 100%;" prop="jobselected">
                            <el-select v-model.number="form.jobselected" placeholder="请选择岗位" style="width: 100%;">
                                    <el-option :label="item.postName" :value="item.postId" v-for="item in form.job" :key="item.postId"></el-option>
                            </el-select>
                    </el-form-item>
                </el-col>
            </el-form>
            <div slot="footer" class="dialog-footer btn_footer">
                <el-button @click="resetForm('form')">取 消</el-button>
                <el-button type="primary" @click="submitForm('form')">确 定</el-button>
            </div>
            </el-dialog>
            
            <button class="bt btn" @click="deleteAll()">-删除角色</button>
        </div>
        <!-- <div class="show">
            <router-view></router-view>
        </div> -->
        <h3 class="bg_thead m-0 p-2">用户管理</h3>
        <table class="table">
            <thead class="bg_thead">
                <th><input type="checkbox" v-model="check" @change="checked()"></th>
                <th>用户名</th>
                <th>工号</th>
                <th>电话号码</th>
                <th>所属部门</th>
                <th>电子邮件</th>
                <th>直属上级</th>
                <th>角色</th>
                <th>出生年月</th>
                <th>入职时间</th>
                <th>性别</th>
                <th>状态</th>
                <th>操作</th>
            </thead>
            <tbody v-for="item in getList" :key=item.id> 
                <tr>
                    <td><input type="checkbox" v-model="item.check" @change="changeC()"></td>
                    <td>{{item.username}}</td>
                    <td>{{item.userId}}</td>
                    <td>{{item.phone}}</td>
                    <!-- <td>{{22}}</td> -->
                    <td>{{item.department.departName}}</td>
                    <td>{{item.mail}}</td>
                    <td>{{item.parentId}}</td>
                    <!-- <td>{{item.role}}</td> -->
                    <td>{{item.role.roleName}}</td>
                    <td>{{item.birth}}</td>
                    <td>{{item.time}}</td>
                    <td>{{item.gender}}</td>
                    <td>{{item.state}}</td>
                    <td>
                        <a href="#" @click="revise(item.userId)">修改 &nbsp;</a>
                        <a href="#" @click="deleteD(item.userId)">注销 &nbsp;</a>
                        <a href="#">密码重置</a>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="form-inline">
        <select name="" @change="cha($event)" class="form-control" style="margin:0 5px">
            <option v-for="item in optList" :value="item.val">{{item.val}}</option>
        </select>
        <button @click="change(-1)" class="btn btn-primary" style="margin:0 5px">上一页</button>
        <input type="text" class="form-control text-center" v-model="currPage" style="width: 60px;margin:0 5px">页
        <button @click="change(1)" class="btn btn-primary"  style="margin:0 5px">下一页</button>
        <span class="fr">当前显示{{(currPage-1)*pageSize+1}}-{{currPage*pageSize}}
            条数据，共显示{{totalSize}}条数据</span>
              
        </div>
    </div>
</template>
<script>
    export default{
        data(){
            return {
                title:'',
                currPage:1,
                state:0,
                stateUp:0,
                id:'',
                userId:null,
                username:null,
                pageSize:5,
                getList:[],
                check:false,
                totalPage:"",
                totalSize:"",
                optList:[
                    {val:5},
                    {val:1},
                    {val:2},
                    {val:3},
                    {val:4},
                    {val:5},
                    {val:6},
                    {val:7},
                    {val:8},
                    {val:9},
                    {val:10}
                ],
                dialogTableVisible: false,
                dialogFormVisible: false,
                props:{
                    value:'roleId',
                    label:'roleName',
                    children:'children'
                },
                form: {
                    userId:'',
                    sex:"",
                    regionselected:'',
                    region:[
                        // {id:0,label:"陆军军",val:'0'},
                        // {id:1,label:"薛志养",val:'1'},
                        // {id:2,label:"鱼雷",val:'2'}
                    ],
                    gradeselected:'',
                    grade:[
                        {id:0,label:"初级",value:'0'},
                        {id:1,label:"中级",value:'1'},
                        {id:2,label:"高级",value:'2'}
                    ],
                    email:'',
                    entry: '',
                    salary:'',
                    name: '',
                    tel:'',
                    selectedOptions: [],
                    birth: '',
                    companyselected:'',
                    company:[
                        // {id:0,label:"苏州总部",val:'0'},
                        // {id:1,label:"上海分公司",val:'1'},
                        // {id:2,label:"办事处",val:'2'}
                    ],
                    jobselected:'',
                    job:[
                        // {id:0,label:"web",val:'0'},
                        // {id:1,label:"java",val:'1'},
                        // {id:2,label:"ui",val:'2'}
                    ],
                    delivery: false,
                    type: [],
                    resource: '',
                    desc: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入活动姓名', trigger: 'blur' }
                        ],
                    userId: [
                        { required: true, message: '请输入用户工号', trigger: 'blur' }
                    ],
                    sex:[
                        { required: true, message: '请选择性别', trigger: 'change' }
                    ],
                    regionselected:[
                        { required: true, message: '请选择直属上级', trigger: 'change' }
                    ],
                    email:[
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    entry: [
                        { //type: 'date',
                         required: true, message: '请选择日期', trigger: 'change' }
                    ],
                    gradeselected:[
                        { required: true, message: '请选择级别', trigger: 'change' }
                    ],
                    birth: [
                        { //type: 'date', 
                        required: true, message: '请选择日期', trigger: 'change' }
                    ],
                    tel: [
                        { required: true, message: '请输入号码', trigger: 'blur' },
                        // { type: 'number', message: '号码为数字值'}
                    ],
                    salary:[
                        { required: true, message: '请输入薪水', trigger: 'blur' },
                        { type: 'number', message: '薪水必须为数字'}
                    ],
                    companyselected:[
                        { //type: 'number', 
                        required: true, message: '请至少选择一个公司', trigger: 'change' }
                    ],
                    selectedOptions:[
                        { type: 'array',
                        required: true, message: '请选择部门', trigger: 'change' }
                    ],
                    jobselected:[
                        { //type: 'number',
                        required: true, message: '请选择岗位', trigger: 'change' }
                    ]
                },
                formLabelWidth: '100px',
                share:{
                    selectedOptionsT: [],
                },
                options: [{
                    value:'',
                    label:'',
                    children:[]
                }],
                optionsT:[],
                optionsLabel:[],
                deleteA:[],
                deleteN:[]
            }
        },
        methods:{
            //获取数据
            getData(){
                var url = "/xc/user/query";
                this.axios.get(url,{params:{
                    currPage:this.currPage,
                    PAGE_SIZE:this.pageSize
                }}).then(res=>{
                    console.log(1)
                    console.log(res.data)
                    this.getList = res.data.data.data;
                    this.getList.forEach(item=>{
                        this.$set(item,'check',false);
                    })
                    this.totalPage = res.data.data.totalPage;
                    this.totalSize = res.data.data.totalCount;
                    console.log(this.totalSize)
                    console.log(res.data.data.data[0])
                })
            },
            //查询
            getL(){
                var url = "/xc/user/query";
                var select = {params:{
                    currPage:this.currPage,
                    PAGE_SIZE:this.pageSize,
                    userId:this.userId,
                    username:this.username
                }};
                this.axios.get(url,select).then(res=>{
                    this.getList = res.data.data.data;
                    this.state = 1;
                    this.totalSize = res.data.data.totalCount;
                    this.totalPage = res.data.data.totalPage;
                })
            },
            //company
            getCompany(){
                var url = "/xc/user/queryCompany";
                this.axios.get(url).then(res=>{
                    this.form.company = res.data.data;
                    console.log("公司")
                    console.log(this.form.company)
                })
            },
            //job
            getJob(){
                var url = "/xc/user/queryPost";
                this.axios.get(url).then(res=>{
                    this.form.job = res.data.data;
                    console.log("岗位")
                    console.log(this.form.job)
                })
            },
            //region
            getRegion(){
                var url = "/xc/user/queryBoss";
                this.axios.get(url).then(res=>{
                    this.form.region = res.data.data;
                    console.log("上级")
                    console.log(this.form.region)
                })
            },
            //用户部门
            getTree(){
                var url = "/xc/user/queryDepartment";
                this.axios.get(url).then(res=>{
                   this.options = res.data.data;
                   console.log("部门")
                   console.log(this.options)
                   this.options = this.options.map(function(item){
                        return{
                            "value":item.departId,
                            "label":item.departName,
                            'children':item.children
                        }
                   })
                   for(var key of this.options){
                        //更改键值
                        key.children = key.children.map(function(item){
                            return{
                                "value":item.departId,
                                "label":item.departName
                            }
                        })
                    }
                    console.log("更改后部门")
                    console.log(this.options)
                })
            },
            getAll(){
                // this.resetForm(formName);
                this.title = "新增用户";
                if(this.stateUp == 1){
                    // this.resetForm(formName);
                    this.clearAll();
                }
                this.dialogFormVisible = true;
                this.stateUp = 0;
                this.getCompany();
                this.getTree();
                this.getJob();
                this.getRegion()
            },
            // 分配角色
            getShare(){
                this.dialogTableVisible = true;
                var url = "/xc/user/queryRole";
                this.axios.get(url).then(res=>{
                    this.optionsT = res.data.data;
                    for(let i=0;i<2;i++){
                        for(let j=0;j<2;j++){
                            var len = res.data.data.length;
                            let op = res.data.data[0].children[i].children[j]
                            if(op.children.length == 0){
                                delete op.children;
                            }
                        }
                    }
                    console.log("分配角色")
                    console.log(this.optionsT)
                })
            },
            // 取消分配角色
            dshare(){
                this.dialogTableVisible = false;
                this.form.selectedOptionsT = [];
            },
            // 提交分配角色
            submitShare(){
                this.dialogTableVisible = false;
                var url = "/xc/user/updateRole";
                var data ={userId:this.deleteA[0],roleId:this.share.selectedOptionsT[2]}
                this.axios.post(url,this.qs.stringify(data)).then(res=>{
                    this.getData();
                })
            },
            //提交并审核
            submitForm(formName) {
                    this.$refs[formName].validate((valid) => {
                    if (valid) {
                        alert('成功!');
                        var obj = {
                            // roleId:'',
                            userId:this.form.userId,
                            username:this.form.name,
                            companyId:this.form.companyselected,
                            phone:this.form.tel,
                            mail:this.form.email,
                            gender:this.form.sex,
                            birth:this.form.birth,
                            time:this.form.entry,
                            level:this.form.gradeselected,
                            salary:this.form.salary,
                            departId:this.form.selectedOptions[1],
                            postId:this.form.jobselected,
                            parentId:this.form.regionselected
                        };
                        if(this.stateUp == 0){
                            // 新增
                            var url = "/xc/user/add";
                        }else{
                            // 更新
                            var url = "/xc/user/update";
                            obj.id = this.id;
                        }
                        this.axios.post(url,this.qs.stringify(obj)).then(res=>{
                            
                            this.dialogFormVisible = false;
                            // this.resetForm(formName);
                            var url = "/xc/user/query";
                            var select = {params:{
                                currPage:1,
                                PAGE_SIZE:this.pageSize,
                                userId:this.form.userId,
                                username:this.form.name
                            }};
                            this.axios.get(url,select).then(res=>{
                                this.getList = res.data.data.data;
                                this.totalSize = res.data.data.totalCount;
                                this.totalPage = res.data.data.totalPage;
                                this.state = 1;
                                // this.currPage = 1;
                                this.resetForm(formName);
                            })
                            
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                    });
            },
            // 清除所有
            clearAll(){
                    this.form.userId = '';
                    this.form.name = '';
                    this.form.companyselected = '';
                    this.form.tel = '';
                    this.form.email = '';
                    this.form.sex = '';
                    this.form.birth = '';
                    this.form.entry = '';
                    this.form.gradeselected = '';
                    this.form.salary = '';
                    this.form.selectedOptions[1] = '';
                    this.form.jobselected = '';
                    this.form.regionselected = '';
                    this.id = ''
            },
            // 取消
            resetForm(formName) {
                this.dialogFormVisible = false;
                if(this.stateUp == 0){
                    this.$refs[formName].resetFields();
                }
            },
            // 修改
            revise(value){
                this.dialogFormVisible = true;
                this.getAll();
                this.title = "修改信息";
                this.stateUp = 1;
                var url = "/xc/user/preUpdate";
                this.axios.get(url,{params:{userId:value}}).then(res=>{
                    // console.log(222)
                    // console.log(res.data.data);
                    var arr = res.data.data;
                    console.log(123)
                    console.log(arr)
                    this.form.userId = arr.userId;
                    this.form.name = arr.username;
                    this.form.companyselected = arr.company.companyId;
                    this.form.tel = arr.phone;
                    this.form.email = arr.mail;
                    this.form.sex = arr.gender;
                    this.form.birth = arr.birth;
                    this.form.entry = arr.time;
                    this.form.gradeselected = arr.level;
                    this.form.salary = arr.salary;
                    this.form.selectedOptions = [];
                    this.form.selectedOptions.push(this.options[0].value,arr.department.departId);
                    // this.form.selectedOptions[1] = arr.department.departId;
                    this.form.jobselected = arr.post.postId;
                    this.form.regionselected = arr.parentId;
                    this.id = arr.id;
                    console.log(3)
                    console.log(this.form.selectedOptions)
                    console.log(1+'---'+this.options[0].value+'--'+this.form.selectedOptions)
                })
                

            },
            //单个注销
            deleteD(value){   
                var url = "/xc/user/delMore";
                this.deleteN=[value];
                console.log(this.deleteN)
                if(confirm('确定要删除')){
                    this.axios.post(url,this.qs.stringify({userIds:this.deleteN},{indices:false})).then(res=>{
                    console.log(this.deleteA);
                    this.getData();
                    this.deleteN=[];
                    console.log(this.deleteN)
                })
                } 
            },
            // 批量删除
            deleteAll(){
                var url = "/xc/user/delMore";
                if(confirm('确定要删除吗？')){
                    this.axios.post(url,this.qs.stringify({userIds:this.deleteA},{indices:false})).then(res=>{
                    console.log(this.deleteA)
                    this.getData();
                })
                }
            },
            // 复选框控制所有
            checked(){
                this.getList.forEach(element => {
                    console.log(element);
                    element.check=this.check;
                });
                if(this.check == true){
                    var count = 0;
                    this.getList.forEach(element => {
                        count++;
                        this.deleteA[count-1]=element.userId;
                        console.log(this.deleteA)
                    });
                }else{
                    this.deleteA =[]
                }
            },
            // 单个复选框
            changeC(){
                var count = 0;
                this.getList.forEach(element => {
                    console.log(1)
                    console.log(element.check);
                    if(element.check == true){
                        count++;
                        this.deleteA[count-1]=(element.userId);
                        this.deleteA.splice(count)
                        console.log(this.deleteA)
                    }
                });
                if(count == this.pageSize){
                    this.check = true
                }else{
                    this.check = false;
                }
            },
            //上一页
            change(i){
                this.check = false;
                if(this.currPage<this.totalPage || i==-1){
                    if(this.currPage>1 || i==1){
                        this.currPage += i;
                        if(this.state == 0){
                            this.getData()
                        }else{
                            this.getL()
                        }
                    }
                }
            },
            //清空
            clear(){
                // this.username = "";
                // this.userId = "";
                // this.currPage = 1;
                // this.state =0;
                // this.pageSize = 5;
                // this.getData();
                location. reload()
                // this.$router.go(0)
            },
            //select框选择值
            cha(event){
                this.pageSize = event.target.value;
                if(this.state == 0){
                    this.getData()
                }else{
                    this.getL()
                }
            },
            handleNodeClick(data) {
                console.log(data);
            }
        },
        mounted(){
            this.getData();
        },
        watch: {
          'currPage': function(newVal){
              this.currPage = parseInt(newVal);
              if(isNaN(this.currPage)){
                  this.currPage = 1
              }
              if(this.currPage>this.totalPage){
                  this.currPage = this.totalPage
              }
              if(this.state == 0){
                    this.getData()
                }else{
                    this.getL()
                }
          },
          'username':function(newVal){
              this.currPage = 1;
              
          },
          "userId":function(newVal){
              this.currPage = 1;
              
          }
      }
        
    }
</script>
<style>
*{
    margin: 0;
    padding: 0;
}
.user{
    text-align: left
}
.bt{
    background-color: rgb(149, 173, 228);
    padding: 0 15px;
    color: #ffffff;
    margin-left: 8px;
}
table>thead>th{
    border: 1px solid #dddddd;
    padding: 3px 15px;
    text-align: center
}
.bg_thead{
    /* background-color: #E9F0FF; */
}
table>tbody{
    text-align: center !important
}
table>tbody>tr>td{
    border: 1px solid #dddddd
}
.btn_op{
    padding: 0 8px;
}
.wb{
    width: 50px;
    height: 30px;
}
.fr{
    float: right;
}
.btn_footer{
    position: relative;
    top: 10px;
    right: 230px;
}
.el-select-dropdown__item{
    overflow: visible !important;
}
#cortxt.el-input__inner:hover{
    cursor: text !important;
}
.dropdown{
    width: 50px;
    height: 30px;
    /* border-radius: 5px; */
}
</style>